﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace PhoneAppRssReader.Converter
{
    public class DateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value", "Value can not be null");
            }
            if (!(value is DateTime))
            {
                throw new ArgumentException("Value must be of type DateTime", "value");
            }

            var dt = (DateTime)value;
            if (dt == System.Convert.ToDateTime("1/1/0001 12:00:00 AM"))
            {
                dt = DateTime.Now;
            }
            if (parameter == null)
            {
                // Date "7/27/2011 9:30:59 AM" returns "7/27/2011"
                return string.Format("{0:h:mm tt MMM/dd/yyyy}", dt);
            }
            switch ((string)parameter)
            {
                case "day":
                    {
                        // Date "7/27/2011 9:30:59 AM" returns "27"
                        return string.Format("{0:dd}", dt);
                    }
                case "month":
                    {
                        // Date "7/27/2011 9:30:59 AM" returns "JUL"
                        return string.Format("{0:MMM}", dt);
                    }
                case "year":
                    {
                        // Date "7/27/2011 9:30:59 AM" returns "2011"
                        return string.Format("{0:yyyy}", dt);
                    }
                default:
                    {
                        // Requested format is unknown. Return in the original format.
                        return dt.ToString(CultureInfo.InvariantCulture);
                    }
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var strValue = value as string;
            DateTime resultDateTime;
            return DateTime.TryParse(strValue, out resultDateTime) ? resultDateTime : value;
        }
    }
}